package com.it.schoolbookshop_back.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.enums.UserRoleEnums;
import com.it.schoolbookshop_back.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminInterfaceVerifyRole implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(AdminInterfaceVerifyRole.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对于OPTIONS请求直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        
        String path = request.getRequestURI();
        String username = UserContext.getUsername();
        String userRole = UserContext.getRole();
        String adminRoleName = UserRoleEnums.ADMIN.name();

        // 输出调试信息
        logger.info("AdminInterfaceVerifyRole 调试信息:");
        logger.info("请求路径: {}", path);
        logger.info("当前用户: {}", username);
        logger.info("用户角色: {}", userRole);
        logger.info("管理员角色名称: {}", adminRoleName);
        
        // 不区分大小写比较角色
        boolean isAdmin = userRole != null && userRole.equalsIgnoreCase(adminRoleName);
        logger.info("角色比较结果(忽略大小写): {}", isAdmin);

        // 检查是否是管理员接口
        if (path.contains("/api/admin")) {
            logger.info("检测到管理员接口访问: {} 用户: {}", path, username);
            
            // 验证用户角色是否为管理员（不区分大小写）
            if (!isAdmin) {
                logger.warn("非管理员用户: {} 尝试访问管理员接口: {}, 用户角色: {}", username, path, userRole);
                
                // 设置响应类型和状态码
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                
                // 返回错误信息
                Result<?> result = Result.failed(403, "权限不足，需要管理员权限");
                response.getWriter().write(objectMapper.writeValueAsString(result));
                return false;
            }
            
            logger.info("管理员用户: {} 成功访问管理员接口: {}", username, path);
        }
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空ThreadLocal中的数据
        UserContext.clear();
        
        // 记录异常信息
        if (ex != null) {
            logger.error("请求处理过程中发生异常: {}", ex.getMessage(), ex);
        }
    }
}
